<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="标题" prop="title">
        <el-input v-model="queryParams.title" placeholder="请输入标题" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="来源" prop="source">
        <el-input v-model="queryParams.source" placeholder="请输入来源" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <!-- <el-form-item label="作者id" prop="authorUserId">
        <el-input v-model="queryParams.authorUserId" placeholder="请输入作者id" clearable
          @keyup.enter.native="handleQuery" />
      </el-form-item> -->
      <el-form-item label="作者姓名" prop="authorUserName">
        <el-input v-model="queryParams.authorUserName" placeholder="请输入作者姓名" clearable
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <!-- <el-form-item label="操作人ID" prop="operatorUserId">
        <el-input v-model="queryParams.operatorUserId" placeholder="请输入操作人ID" clearable
          @keyup.enter.native="handleQuery" />
      </el-form-item> -->
      <!-- <el-form-item label="小鹅通视频链接" prop="xetUrl">
        <el-input v-model="queryParams.xetUrl" placeholder="请输入小鹅通视频链接" clearable @keyup.enter.native="handleQuery" />
      </el-form-item> -->
      <el-form-item label="上线状态" prop="onlineState">
        <!-- stateList -->
        <el-select v-model="queryParams.onlineState" placeholder="请输入上线状态" clearable @change="handleQuery">
          <el-option v-for="item in stateList" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['busines:article:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['busines:article:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['busines:article:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['busines:article:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="articleList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <!-- <el-table-column label="文章数据ID" align="center" prop="articleId" /> -->
      <el-table-column label="标题" align="left" prop="title" />
      <el-table-column label="封面图片URL" align="center" prop="coverUrl">
        <template slot-scope="scope">
          <el-image style="width: 100px; height: 100px" :src="scope.row.coverUrl"></el-image>
        </template>
      </el-table-column>
      <!-- <el-table-column label="内容" align="center" prop="content" /> -->
      <!-- <el-table-column label="富文本内容包含资源url(逗号分割)(待定字段)" align="center" prop="contentUrl" /> -->
      <el-table-column label="来源" align="center" prop="source" />
      <!-- <el-table-column label="作者id" align="center" prop="authorUserId" /> -->
      <el-table-column label="作者姓名" align="left" prop="authorUserName" />
      <!-- <el-table-column label="操作人ID" align="center" prop="operatorUserId" /> -->
      <el-table-column label="文章类型" align="center" prop="articleType">
        <template slot-scope="scope">
          <div>{{ LabelArticleType(scope.row.articleType) }}</div>
        </template>
      </el-table-column>
      <el-table-column label="小鹅通视频链接" align="center" prop="xetUrl" :show-overflow-tooltip="true" />
      <el-table-column label="上线状态" align="center" prop="onlineState">
        <template slot-scope="scope">
          {{ LabelOnlineState(scope.row.onlineState) }}
        </template>
      </el-table-column>
      <!-- <el-table-column label="是否删除   -1：已删除，0：未删除" align="center" prop="isDelete" /> -->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['busines:article:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['busines:article:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改文章对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="940px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入标题" />
        </el-form-item>
        <el-form-item label="封面图片URL" prop="coverUrl">
          <commonImgUpload v-model="form.coverUrl" @backUrl="backUrl"></commonImgUpload>
        </el-form-item>
        <el-form-item label="文章类型" prop="articleType">
          <el-select v-model="form.articleType" placeholder="请选择文章类型">
            <el-option v-for="item in articleLists" :key="item.label" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="个人或机构" class="persong_org" prop="selectedCategory">
          <div style="display: flex;" >
            <el-radio-group v-model="selectedCategory" @change="handleCategoryChange" style="margin-right: 20px;">
              <el-radio-button label="institution">机构</el-radio-button>
              <el-radio-button label="personal">个人</el-radio-button>
            </el-radio-group>
            <!-- 第二步：根据选中的类别显示相应的选择器 -->
            <el-select v-if="selectedCategory === 'institution'" v-model="selectedItem" placeholder="请选择机构医谱号">
              <!-- <el-option v-for="item in originalData.institution" :key="item.id" :label="item.nickName" :value="item"> -->
              <el-option v-for="item in originalData.institution" :key="item.id" :label="insNickName(item)"
                :value="item.nickName">
              </el-option>
            </el-select>
            <el-select v-else-if="selectedCategory === 'personal'" v-model="selectedItem" placeholder="请选择个人医谱号">
              <!-- <el-option v-for="item in originalData.personal" :key="item.id" :label="item.nickName" :value="item"></el-option> -->
              <el-option v-for="item in originalData.personal" :key="item.id" :label="personNickName(item)"
                :value="item.nickName">
              </el-option>
            </el-select>
          </div>
        </el-form-item>
        <el-form-item label="作者id" prop="authorUserId">
          <el-input v-model="form.authorUserId" disabled placeholder="请输入作者id" />
        </el-form-item>
        <el-form-item label="作者姓名" prop="authorUserName">
          <el-input v-model="form.authorUserName" disabled placeholder="请输入作者姓名" />
        </el-form-item>
        <el-form-item label="小鹅通视频链接" prop="xetUrl">
          <el-input v-model="form.xetUrl" placeholder="请输入小鹅通视频链接" />
        </el-form-item>
        <!-- <el-form-item label="内容">
          <editor v-model="form.content" :min-height="192" />
        </el-form-item> -->
        <el-form-item label="来源" prop="source">
          <el-input v-model="form.source" placeholder="请输入来源" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listArticle, getArticle, delArticle, addArticle, updateArticle, getAuthorList } from "@/api/system/article";
import commonImgUpload from "@/components/commonImgUpload";
export default {
  //dicts: ['doctor_rank'],
  components: { commonImgUpload },
  name: "Article",
  data() {
    return {
      selectedCategory: '', // 用于存储选中的类别（institution 或 personal）
      selectedItem: null, // 用于存储选中的对象
      originalData: {
        // 这里是你的原始数据
        "institution": [],
        "personal": []
      },
      articleLists: [  //1：文章，2：视频，3：音频
        { value: "1", label: "图文" },
        { value: "2", label: "视频" },
        { value: "3", label: "音频" },
      ],
      stateList: [
        { value: "0", label: "上线" },
        { value: "1", label: "下线" }
      ],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 文章表格数据
      articleList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        title: null,
        coverUrl: null,
        content: null,
        contentUrl: null,
        source: null,
        authorUserId: null,
        authorUserName: null,
        operatorUserId: null,
        articleType: null,
        xetUrl: null,
        onlineState: null,
        isDelete: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        authorUserName: [
          { required: true, message: "作者姓名不能为空", trigger: "blur" }
        ],
        authorUserId: [
          { required: true, message: "作者ID不能为空", trigger: "blur" }
        ],
        createTime: [
          { required: false, message: "创建时间不能为空", trigger: "blur" }
        ],
        xetUrl: [
          { required: true, message: "小鹅通视频链接不能为空", trigger: "blur" }
        ],
        articleType: [
          { required: true, message: "文章类型不能为空", trigger: "blur" }
        ],
        title: [
          { required: true, message: "标题不能为空", trigger: "blur" }
        ],
        coverUrl: [
          { required: true, message: "封面图片URL不能为空", trigger: "blur" }
        ],
        selectedCategory: [
          { required: false, message: "请选择个人或者机构", trigger: "change" }
        ]
      }
    };
  },
  created() {
    this.getList();
  },
  computed: {
    LabelArticleType() {
      return (val) => {
        if (!val) return "暂无"
        if (val == 1) return "图文"
        else if (val == 2) return "视频"
        else if (val == 3) return "音频"
      }
    },
    LabelOnlineState() {
      return (val) => {
        if (val == null) return "暂无"
        if (val == 0) return "上线"
        else if (val == 1) return "下线"
      }
    },
    personNickName() {
      return (obj) => {
        let nickName = obj.nickName
        let depNmame = obj.deptName
        let institutionName = obj.institutionName
        let mystring = nickName + "/" + depNmame + "/" + institutionName
        // console.log(, 111);
        return mystring
      }
    },
    insNickName() {
      return (obj) => {
        //  console.log(obj,'obj');
        let nickName = obj.nickName
        let institutionName = obj.institutionName
        let mystring = nickName + "/" + institutionName
        return mystring
      }
    }
  },
  watch: {
    selectedItem: {
      handler(val, oldVal) {
        if (val) {
          if (this.selectedCategory === 'institution') {
            this.form.authorUserId = this.originalData.institution.find(item => item.nickName == val).userId;
          }
          if (this.selectedCategory === 'personal') {
            this.form.authorUserId = this.originalData.personal.find(item => item.nickName == val).userId;
          }
          this.form.authorUserName = val;
        }
      },
      deep: true
      // ,immediate:true
    }
  },
  methods: {
    // showDocLabel(val) {
    //   let find = this.dict.type.doctor_rank.find(item => item.value == val)
    //   if (find) {
    //     return find.label
    //   } else {
    //     return "暂无职称"
    //   }
    // },
    handleCategoryChange() {
      // 当选中的类别改变时，重置 selectedItem
      if (this.selectedItem && this.selectedItem.type !== this.selectedCategory) {
        this.selectedItem = null;
        this.form.authorUserName = null;
        this.form.authorUserId = null;
        // this.$refs["searchForm"].clearValidate();
      }
    },
    /** 查询文章列表 */
    getList() {
      this.loading = true;
      listArticle(this.queryParams).then(response => {
        this.articleList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    backUrl(val) {
      this.form.coverUrl = val;
      console.log(this.form.coverUrl);
    },
    // 表单重置
    reset() {
      this.form = {
        articleId: null,
        title: null,
        coverUrl: null,
        content: null,
        contentUrl: null,
        source: null,
        authorUserId: null,
        authorUserName: null,
        operatorUserId: null,
        articleType: null,
        xetUrl: null,
        onlineState: null,
        isDelete: null,
        createTime: null,
        updateTime: null
      };
      this.selectedCategory = null;
      this.selectedItem = null;
      this.form.authorUserName = null;
      this.form.authorUserId = null;
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.articleId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加文章";
      this.getUserList();
    },
    async getUserList() {
      let res = await getAuthorList()
      if (res.code == 200) {
        this.originalData.institution = res.data && res.data.institution;
        this.originalData.personal = res.data && res.data.personal;
        //console.log(this.originalData);
        //this.userList = res.data
      }
      // console.log(this.originalData);
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const articleId = row.articleId || this.ids
      getArticle(articleId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改文章";
        this.getUserList();
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.articleId != null) {
            updateArticle(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addArticle(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const articleIds = row.articleId || this.ids;
      this.$modal.confirm('是否确认删除文章编号为"' + articleIds + '"的数据项？').then(function () {
        return delArticle(articleIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/article/export', {
        ...this.queryParams
      }, `article_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
<style scoped lang="scss">
.persong_org{
  &::before{
    content: "*";
    z-index: 2;
    position: absolute;
    left: 48px;
    top: 422px;
    color: red;
  }

}
</style>
